import { observable, action, autorun, toJS } from 'mobx';
import { WeaTools, WeaLocaleProvider, WeaBrowser, WeaFormItem } from 'ecCom';
import { message, Modal } from 'antd';
import * as Apis from '../apis/highSeas';
import { WeaTableNew, WeaForm } from 'comsMobx';
import conditionDialogStore from './ConditionDialogStore';

const { TableStore } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;


export default class HighSeasSettingFormStore {
    @observable tableStore1 = new TableStore();
    @observable sessionkey1 = '';
    @observable tableStore2 = new TableStore();
    @observable sessionkey2 = '';
    @observable tabKey = 0;
    @observable formInfo = {};
    @observable seasCloseInfo = {};
    @observable seasCloseModal = { visible: false };
    @observable right = '';// 表单权限
    @observable verified = false;
    @observable visible = false;
    @observable checkCrmNumModel = { visible: false, title: '', loading: false, nums: { num1: 0, num2: 0 }, disabled: false };
    manager4close;
    highSeasSettingFormComp;
    @observable conditionDialogStore = new conditionDialogStore();

    @action
    checkForm=params => this.highSeasSettingFormComp.checkForm(params)
    @action
    initForm=(params = {}, highSeasSettingForm) => {
      const that = this;
      if (highSeasSettingForm) {
        this.highSeasSettingFormComp = highSeasSettingForm;
      }
      this.verified = false;
      this.changeTab(0);
      this.formInfo = {};
      this.sessionkey1 = '';
      this.sessionkey2 = '';
      // this.conditionInfo.fieldOptions = [];
      // this.conditionField = {};
      this.right = '';
      // this.conditionInfo.conditiontype = "1";
      // this.root = {};
      // this.conditionInfo.conditionsql2 = "";
      Apis.getHighSeasInfo('getSettingForm', params).then((data) => {
        this.verified = true;
        if (data.sessionkey1) {
          this.sessionkey1 = data.sessionkey1;
          this.tableStore1.getDatas(data.sessionkey1, 1);
        }
        if (data.sessionkey2) {
          this.sessionkey2 = data.sessionkey2;
          this.tableStore2.getDatas(data.sessionkey2, 1);
        }

        // if(data.fieldOptions){
        //     this.conditionInfo.fieldOptions = data.fieldOptions;
        // }

        // if(data.conditionField){
        //     this.conditionField = data.conditionField;
        // }

        if (data.right) {
          this.right = data.right;
        } else {
          this.right = '';
        }

        this.formInfo = { ...params, ...data.datas };
        if (data.datas && data.datas.customerScope) {
          const customerScope = JSON.parse(data.datas.customerScope);
          const papp = { mainTablename: 'CRM_CustomerInfo', customerScope };
          that.conditionDialogStore.init(papp, that.setFormInfo, that.onCancel);
          that.conditionDialogStore.mask = false;


          // const customerScope = JSON.parse(data.datas.customerScope);
          // const param = customerScope.param;
          // this.conditionInfo.conditiontype = param.conditiontype;
          // if(param.conditiontype=="1"){
          //     if(param.rootdata){
          //         this.root = param.rootdata;
          //     }
          // }else{
          //     let Base64 = WeaTools.Base64;
          //     let sql = Base64.decode(param.conditionsql);
          //     this.conditionInfo.conditionsql2 = sql;
          // }
        } else {
          const papp = { mainTablename: 'CRM_CustomerInfo', customerScope: null };
          that.conditionDialogStore.init(papp, that.setFormInfo, that.onCancel);
          that.conditionDialogStore.mask = false;
          // this.root = {};
          // this.conditionInfo.conditionsql2 = '';
        }
      });
    }

    @action
    setFormInfo = (params) => {
      this.formInfo = { ...this.formInfo, ...params };
    }

    @action
    changeTab = (tabKey) => {
      this.tabKey = tabKey;
    }

    @action
    saveAuthInfo = (params) => {
      const req = { ...params, seasId: this.formInfo.editId };
      Apis.getHighSeasInfo('doSaveAuth', req).then((data) => {
        this.reload(params.table);
        message.success(getLabel('384136', '操作成功!'));
      });
    }


    @action
    deleteAuth = (table) => {
      const that = this;
      Modal.confirm({
        title: getLabel(33475, '确认要删除选中记录吗？'),
        onOk() {
          let param;
          if (table == 't1')param = { table, delIds: `${that.tableStore1.selectedRowKeys}` };
          if (table == 't2')param = { table, delIds: `${that.tableStore2.selectedRowKeys}` };
          that.saveAuthInfo(param);
        },
        onCancel() {},
      });
    }

    @action
    reload = (table) => {
      if (table == 't1') this.tableStore1.getDatas(this.sessionkey1, this.tableStore1.current);
      if (table == 't2') this.tableStore2.getDatas(this.sessionkey2, this.tableStore2.current);
    }

    @action
    seasClose = (param = {}) => {
      this.seasCloseInfo = param;
    }

    @action
    checkCrmNum = (value) => {
      this.setFormInfo({ status: value });
      if (value == 0) {
        if (this.formInfo.editId) {
          const param = { seasId: this.formInfo.editId, operation: 'getNum' };
          Apis.getHighSeasInfo('seasClose', param).then((data) => {
            this.checkCrmNumModel.visible = (data.datas && data.datas.num1 > 0);
            this.checkCrmNumModel.nums = data.datas;
          });
        }
      }
    }

    @action
    checkCrmNumOnOK=() => {
      if (this.checkCrmNumModel.nums.num1 > 0 && this.seasCloseInfo.manager) {
        this.checkCrmNumModel.loading = true;
        this.checkCrmNumModel.disabled = true;
        Apis.getHighSeasInfo('seasClose', { operation: 'save', seasId: this.formInfo.editId, manager: this.seasCloseInfo.manager }).then((data) => {
          message.success(getLabel('384136', '操作成功!'));
          this.seasClose({});
          this.checkCrmNumModel.loading = false;
          this.checkCrmNumModel.disabled = false;
          this.checkCrmNumModel.visible = false;
          this.checkCrmNumModel.nums = { num1: 0, num2: 0 };
        });
      } else {
        this.manager4close.showError();
        // message.error(getLabel('386714',"未选择指定客户经理！"));
        this.seasClose({});
      }
    }

    @action
    checkCrmNumOnCancel=() => {
      this.checkCrmNumModel.loading = false;
      this.checkCrmNumModel.nums = { num1: 0, num2: 0 };
      this.checkCrmNumModel.visible = false;
      this.seasClose({});
      this.setFormInfo({ status: 1 });
    }

    // @observable conditionInfo = {
    //     "conditionsql": "",
    //     "conditionsql2": "",
    //     "conditiontext": "",
    //     "conditiontype": "1",
    //     "count": 1,
    //     "detailTables": [],
    //     "mainTablename": "CRM_CustomerInfo",
    //     "fieldOptions":[]
    // };

    // @observable type = "";//类型  modeRight：权限条件
    // @observable objid = "";//所属对象的id
    // @observable visible = false;
    // @observable dialogLoading = false;
    // @observable conditions = {};
    // @observable conditionParam={};//条件参数
    // @observable initParam={};//初始化参数
    // @observable conditionField={};
    // @observable relationtypeOptions =[];

    // @observable fieldRecord={};
    // @observable relation="4";//等于
    // @observable targetValue="";//值
    // @observable targetValueSpan="";//显示名称
    // @observable ismodified="0";//是否修改了

    // @observable root={};
    // @observable selectedItemKey=[];
    // @observable editArr=[];//处于编辑状态的数据
    // @observable selectedItemParentNode="";
    // @observable ruleSql="";
    // @observable ruleSqlText="";
    // @observable isShowSql=false;
    // @observable contentHeight;
    // // @observable conditionSaveCallBack:Function;
    // // @observable toShowErrorSql:Function;
    // @observable dialogName="";//用来解决存在多个dialog的时候，同时打开多个
    // @observable isNeedClose=false;//是否需要关闭dialog
    // @observable isChange=false;//顶部条件是否改变
    // @observable checkButtonDisabled = false;//检查sql按钮默认不置灰

    // @action
    // onSave=()=>{
    //     const {conditiontype,conditionsql2} = this.conditionInfo;
    //     let param = {type:this.type,objid:this.objid,conditiontype:conditiontype,operation:"saveCondition"};
    //     if(conditiontype==1){
    //         if(this.editArr.length>0){
    //             message.error(getLabel(384753,"存在字段处理编辑状态，请编辑好后再进行保存操作"));
    //             return;
    //         }
    //         if(this.isChange == true&&this.targetValue!=""){
    //             let doSaveCondition = this.doSaveCondition;
    //             Modal.confirm({
    //                 title: getLabel(385010,"当前目标字段的值未添加到条件中，是否继续保存？"),
    //                 onOk() {
    //                     doSaveCondition(param);
    //                 },
    //                 onCancel() {},
    //             });
    //         }else{
    //             this.doSaveCondition(param);
    //         }

    //     }else {
    //         // if(trim(conditionsql2)==""){
    //         //     message.error("sql"+getLabel(130806, "不能为空!"));
    //         //     return;
    //         // }
    //         let Base64 = WeaTools.Base64;
    //         let sql = Base64.encode(conditionsql2);
    //         param.conditionsql = sql;
    //         this.isNeedClose = false;
    //         this.setFormInfo({customerScope:JSON.stringify({param})});
    //         this.onCancel();
    //     }

    // }

    // doSaveCondition=(param)=>{
    //     this.getShowSql();
    //     if(this.ruleSql==""){
    //         message.error(getLabel(15364,"条件")+getLabel(130806, "不能为空!"));
    //         return;
    //     }
    //     param.rootdata = this.root;
    //     let Base64 = WeaTools.Base64;
    //     let sql = Base64.encode(this.ruleSql);
    //     let sqlText = Base64.encode(this.ruleSqlText);
    //     param.conditionsql = sql;
    //     param.conditiontext = sqlText;
    //     this.isNeedClose = false;
    //     this.setFormInfo({customerScope:JSON.stringify({param})});
    //     this.onCancel();
    // }

    // deleteCondition=()=>{
    //     let that = this;
    //     let param = {type:this.type,objid:this.objid,operation:"deleteCondition"};
    //     let conditionSaveCallBack = this.conditionSaveCallBack;
    //     this.isNeedClose = true;
    //     Modal.confirm({
    //         title: getLabel(84545,"确定清空所有条件？"),
    //         onOk() {
    //             that.setFormInfo({customerScope:null});
    //             that.onCancel();
    //             that.root = {};
    //             that.ruleSql="";
    //             that.ruleSqlText="";
    //         },
    //         onCancel() {},
    //     });
    // }

    // checkSQL=(toShowErrorSql)=>{
    //     // if(this.ismodified=="1"){
    //     //     message.error(getLabel(82692,"请先保存，再检测条件"));
    //     //     return;
    //     // }
    //     // this.toShowErrorSql = toShowErrorSql;
    //     // let param = {type:this.type,objid:this.objid,operation:"checkSQL"};
    //     this.getShowSql();

    //     // console.log(toJS(this.conditionInfo))
    //     // console.log(toJS(this.ruleSql))

    //     let sql = "";
    //     const conditiontype = this.conditionInfo.conditiontype;
    //     if("1"==conditiontype){
    //         sql = this.ruleSql;
    //     }else{
    //         sql = this.conditionInfo.conditionsql2;
    //     }

    //     if(""==sql){
    //         message.error(getLabel('387163',"没有添加条件，请检查！"));
    //         return;
    //     }
    //     let Base64 = WeaTools.Base64;
    //     sql = Base64.encode(sql);

    //     let params = {checkSQL:sql,operate:"checkSQL"};
    //     this.checkButtonDisabled = true;
    //     Apis.getHighSeasInfo('doSaveForm', params).then(data => {
    //         if(data.errflag){
    //             message.error(data.errMsg);
    //         }else{
    //             message.success(getLabel('387162',"条件检测通过"))
    //         }
    //         this.checkButtonDisabled = false;
    //     })
    // }

    // checkSQLBack=(flag,msg,sql,vdatasource)=>{
    //     if(flag=="1"){
    //         message.success(msg);
    //     }else{
    //         if(sql&&sql!=""){
    //             this.toShowErrorSql(sql,vdatasource);
    //         }else{
    //             message.error(msg);
    //         }
    //     }
    // }


    // @action
    // getShowSql=()=>{
    //     let sql = "";
    //     let sqlText = "";
    //     if(this.root.key&&this.root.key>0){
    //         let obj = this.getSql(this.root,{sql:"",sqlText:""});
    //         sql = obj.sql;
    //         sqlText = obj.sqlText;
    //     }
    //     this.ruleSql = sql;
    //     this.ruleSqlText = sqlText;
    // }

    // @action
    // getSql=(item,{sql,sqlText})=>{
    //     const {isParent} = item;
    //     if(isParent){
    //         const {datas,relationship} = item;
    //         let relation = "AND"
    //         if(relationship=="0"){
    //             relation = "OR";
    //         }
    //         for(let i=0;i<datas.length;i++){
    //             if(i>0){
    //                 sql += " " +relation+ " ";
    //                 sqlText += " " +relation+ " ";
    //             }
    //             if(datas.length>1&&i==0){
    //                 sql += "(";
    //                 sqlText += "(";
    //             }
    //             let obj = this.getSql(datas[i],{sql:"",sqlText:""});
    //             sql += obj.sql;
    //             sqlText += obj.sqlText;
    //             if(datas.length>1&&i==datas.length-1){
    //                 sql += ")";
    //                 sqlText += ")";
    //             }
    //         }
    //     }else{
    //         const {compareopion,tablename,fieldname,htmltype,fieldtype,fieldvalue,fieldlabel,fieldtext} = item;
    //         let relationAndVal = "";
    //         let text = "";
    //         if(fieldvalue=="null"&&(htmltype==5||htmltype==4)){//select或者checkbox 框为null
    //             if(compareopion==4){//等于
    //                 relationAndVal = " is null ";
    //             }else{//不等于
    //                 relationAndVal = " is not null ";
    //             }
    //             text = relationAndVal;
    //         }else{
    //             if(compareopion==6){//包含
    //                 relationAndVal = " like "+"'%"+fieldvalue+"%'";
    //                 text = " like "+"'%"+fieldtext+"%'";
    //             }else if(compareopion==7){//不包含
    //                 relationAndVal = " not like '%"+fieldvalue+"%'";
    //                 text = " like "+"'%"+fieldtext+"%'";
    //             }else {
    //                 var isneedf = true;
    //                 if(htmltype==4){//checkbox
    //                     isneedf = false;
    //                 }else if(htmltype==1&&(fieldtype==2||fieldtype==3)){//整数浮点数
    //                     isneedf = false;
    //                 }else if(htmltype==5){//select框
    //                     isneedf = false;
    //                 }

    //                 let compareoptionStr = "";
    //                 if(compareopion=="0"){
    //                     compareoptionStr = ">";
    //                 }else if(compareopion=="1"){
    //                     compareoptionStr = ">=";
    //                 }else if(compareopion=="2"){
    //                     compareoptionStr = "<";
    //                 }else if(compareopion=="3"){
    //                     compareoptionStr = "<=";
    //                 }else if(compareopion=="4"){
    //                     compareoptionStr = "=";
    //                 }else if(compareopion=="5"){
    //                     compareoptionStr = "!=";
    //                 }else if(compareopion=="100"){
    //                     compareoptionStr = "like";
    //                 }
    //                 if(isneedf){
    //                     relationAndVal = compareoptionStr+" '"+fieldvalue+"'";
    //                 }else{
    //                     relationAndVal = compareoptionStr+" "+fieldvalue;
    //                 }
    //                 text = compareoptionStr+" '"+fieldtext+"'";

    //             }
    //         }


    //         if(compareopion=="5"){
    //             sql +=  "("+tablename+"."+ fieldname+" "+relationAndVal+" or "+ tablename+"."+ fieldname+" is null) ";
    //         }else{
    //             sql +=  tablename+"."+ fieldname+" "+relationAndVal;
    //         }


    //         sqlText +=  fieldlabel+" "+text;
    //     }
    //     return  {sql,sqlText};
    // }

    // getRelationArr=(relationtype)=>{
    //     let arr = new  Array();
    //     if(relationtype=="1"){
    //         arr = [{
    //             key:"4",
    //             showname:getLabel(327,"等于"),
    //         },{
    //             key:"5",
    //             showname:getLabel(15506,"不等于"),
    //         },{
    //             key:"6",
    //             showname:getLabel(346,"包含"),
    //         },{
    //             key:"7",
    //             showname:getLabel(15507,"不包含"),
    //         }];
    //     }else  if(relationtype=="2"){
    //         arr = [{
    //             key:"0",
    //             showname:getLabel(15508,"大于"),
    //         },{
    //             key:"1",
    //             showname:getLabel(325,"大于或等于"),
    //         },{
    //             key:"2",
    //             showname:getLabel(15509,"小于"),
    //         },{
    //             key:"3",
    //             showname:getLabel(326,"小于或等于"),
    //         },{
    //             key:"4",
    //             showname:getLabel(327,"等于"),
    //         },{
    //             key:"5",
    //             showname:getLabel(15506,"不等于"),
    //         }];
    //     }else  if(relationtype=="3"){
    //         arr = [{
    //             key:"4",
    //             showname:getLabel(327,"等于"),
    //         },{
    //             key:"5",
    //             showname:getLabel(15506,"不等于"),
    //         }];
    //     }else  if(relationtype=="4"){
    //         arr = [{
    //             key:"4",
    //             showname:getLabel(327,"等于"),
    //         }];
    //     }
    //     return arr;
    // }

    @action
    onShow=() => {
      this.visible = true;
      this.conditionDialogStore.visible = true;
    }

    @action
    onCancel=() => {
      this.visible = false;
      this.conditionDialogStore.visible = false;
      // this.fieldRecord = {};
    }
}
